<template>
    <div class="comments-container" @mouseenter="pauseScroll" @mouseleave="resumeScroll" :commentList="commentList">
        <div ref="commentsRef" class="comments-scroll" :style="{ 'animation-duration': scrollDuration + 's' }">
            <div v-for="(item, index) in allComments" :key="index" class="comment">
                <a-avatar :src="item.avatar" style="flex-shrink: 0" :size="40" />
                <div>&nbsp;{{ item.content }}</div>
            </div>
        </div>
        <div v-if="allComments.length === 0" class="no-comment">暂无留言</div>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const props = defineProps({
    commentList: {
        type: Array,
        default: () => []
    }
})

// 弹幕滚动时间
const scrollDuration = ref(15);
// 合并原始评论和复制评论
const allComments = ref([])
// 引用DOM元素
const commentsRef = ref(null)
// 滚动状态
const isPaused = ref(false)
// 原始评论数据
const comments = ref();

watch(() => props.commentList, (newValue) => {
    if (newValue.length > 0) {
        scrollDuration.value = newValue.length;
        comments.value = newValue
        allComments.value = [...newValue, ...newValue]
    }
})

// 暂停滚动
const pauseScroll = () => {
    isPaused.value = true
    commentsRef.value.style.animationPlayState = 'paused'
}
// 恢复滚动
const resumeScroll = () => {
    isPaused.value = false
    commentsRef.value.style.animationPlayState = 'running'
}

</script>

<style scoped>
@keyframes scrollUp {
    0% {
        transform: translateY(0);
    }

    100% {
        /* 只滚动一半距离 */
        transform: translateY(-50%);
    }
}

.comments-container {
    overflow: hidden;
    width: 100%;
    height: 300px;

    /* 鼠标悬停时暂停动画 */
    &:hover {
        animation-play-state: paused;
    }

    .comments-scroll {
        animation: scrollUp 15s linear infinite;

        .comment {
            display: flex;
            align-items: center;
            margin: 5px 0;

            div {
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
            }
        }
    }

    .no-comment {
        color: #666;
        text-align: center;
        line-height: 300px;
    }
}
</style>